package controllers;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.apache.commons.io.FilenameUtils;

import utils.UserRoles;


import models.SolutionSubmission;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

@SuppressWarnings("serial")
public class AddSolutionSubmissionServlet extends HttpServlet {
	private BlobstoreService blobstoreService = BlobstoreServiceFactory
			.getBlobstoreService();

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {

		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		String user_email = user.getEmail().toLowerCase();
        String User_Role_String = new UserRoles(user_email).toString();
        String strFile_Name = "";
        String strFile_Key = "";
        
		Date today = new java.util.Date();
		BlobKey blobKey = null;

		String _customer = req.getParameter("cmbCustomer"); // Customer
		String _processArea = req.getParameter("cmbProcessarea"); // processArea
		String _solType = req.getParameter("cmbSolutiontype"); // solType
		String _location = req.getParameter("cmbSite"); // Location

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/mm/dd");
		Date _dtImplemented = null;
		try {
			_dtImplemented = dateFormat.parse(req.getParameter("dtDate"));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String _teamLead = req.getParameter("namSolTL"); // teamLead
		String _teamMembers = req.getParameter("namSolTM"); // teamMembers
		String _namOthTM = req.getParameter("namOthTM"); // namOthTM
		String _title = req.getParameter("txtTheme");// Title;
		String _s1 = req.getParameter("taProbDef");// s1
		String _s2 = req.getParameter("taProbAnalysis");// s2
		String _s3 = req.getParameter("taProbRootCause");// s3
		String _s4 = req.getParameter("taImpSol");// s4
		String _s5 = req.getParameter("taEvalRes");// s5
		String _s6 = req.getParameter("taPrevRec");// s6

		String _chkBenefits = req.getParameter("chkBenefits");// chkBenefits

		String _v1 = (req.getParameter("HardSavings") == "") ? "0" : req
				.getParameter("HardSavings");
		String _v2 = (req.getParameter("CostAvoid") == "") ? "0" : req
				.getParameter("CostAvoid");
		String _v3 = (req.getParameter("OpporCost") == "") ? "0" : req
				.getParameter("OpporCost");

		
		Float _hardSavings = new Float(0); // hardSavings
		Float _costAvoidance = new Float(0); // costAvoidance
		Float _oppurtunityCost = new Float(0); // oppurtunityCost
		
		if(_v1 != null && !_v1.equals("") ) _hardSavings = Float.parseFloat(_v1);// hardSavings
		if(_v2 != null && !_v2.equals("") ) _costAvoidance = Float.parseFloat(_v2);// costAvoidance
		if(_v3 != null && !_v3.equals("") ) _oppurtunityCost = Float.parseFloat(_v3);// oppurtunityCost
		Float _impDays = Float
				.parseFloat((req.getParameter("taImpTime") == "") ? "0" : req
						.getParameter("taImpTime"));// impDays	
		
		
        //EXTRACT THE FILE FROM THE BLOB REQUEST
        @SuppressWarnings("deprecation")
		Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
        if ( blobs != null)
        {
        	blobKey = blobs.get("txtupload_file"); 
        	if ( blobKey != null )
        	{	
        		final BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);  
        		long size = blobInfo.getSize();            	
        		if(size > 0)
        		{
        			//BLOB SELECTED
        			strFile_Name = blobInfo.getFilename();
        			strFile_Name = FilenameUtils.getName(strFile_Name);
        			strFile_Key = blobKey.getKeyString();
        			
        		}else{
        			//NO BLOB SELECTED - delete unnamed blob
        			blobstoreService.delete(blobKey);
        		}
        	}
        }   
        
        
        
		SolutionSubmission newitems = new SolutionSubmission();
		newitems.setTitle(_title);
		newitems.setDtShared(today);
		newitems.setDtImplemented(_dtImplemented);
		newitems.setTeamLead(_teamLead);
		newitems.setTeamMembers(_teamMembers);
		newitems.setOtherTeamMembers(_namOthTM);
		newitems.setCustomer(_customer);
		newitems.setLocation(_location);
		newitems.setProcessArea(_processArea);
		newitems.setSolType(_solType);
		newitems.setTeamPicKey(blobKey);
		newitems.setS1(_s1);
		newitems.setS2(_s2);
		newitems.setS3(_s3);
		newitems.setS4(_s4);
		newitems.setS5(_s5);
		newitems.setS6(_s6);

		// Not Completed
		newitems.setAchievedType(_chkBenefits.toString());
		newitems.setAchievedValue("");
		newitems.setAchievedUnits("");
		// ==============================================

		newitems.setHardSavings(_hardSavings);
		newitems.setCostAvoidance(_costAvoidance);
		newitems.setOppurtunityCost(_oppurtunityCost);

		newitems.setImpDays(_impDays);
		newitems.setAttachKey(blobKey);
		newitems.setStatus("Draft");

		newitems.setSubmittedBY(user_email);
		newitems.setSubmittedON(today);
		newitems.setModifiedBY(user_email);
		newitems.setModifiedON(today);

		// default =========================================== false
		newitems.setMpsCandidate(false);
		newitems.setNominateSolution(false);
		newitems.setBestOfBest(false);
		newitems.setBestOfRegion(false);
		newitems.setBestOfSite(false);
        //========================================================
		
		Objectify ofy = ObjectifyService.begin();
		ofy.put(newitems);
		//UserActionsConnect.AddAction(user_email, "AddSolutionAdoptionServlet", "Inserted solID =" + newitems.getSolID(), "New SolutionSubmission, Blob Filename: " + strFile_Name, User_Role_String, new Date());
        RequestDispatcher rd = req.getRequestDispatcher("/modules/sol/Display-sol-share-solution.jsp");
        rd.forward(req, resp);
        
	}
} // Class End
